package naga.x.net.proxy.codec;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

import naga.x.net.codec.PacketDecoder;
import naga.x.net.codec.StickPacketDecoder;
import naga.x.net.proxy.ProxyPacket;

public class ProxyPacketDecoder extends StickPacketDecoder implements PacketDecoder {

	@Override
	protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
		Object buf = decode(session, in);
		if (buf != null) {
			out.write(buf);
			return true;
		}
		return false;
	}
	
	@Override
	public Object decode(IoSession session, IoBuffer in) {
		if (in.remaining() < 2) { // head 2 bytes
			return null;
		}
		in.mark();
		byte[] head = ProxyPacket.HEAD;
		if (in.get() == head[0] && in.get() == head[1]) {
			if (in.remaining() < 4) { // data length
				in.reset();
				return null;
			}
			int len = in.getInt();
			if (in.remaining() < len) { // 数据包不完整
				in.reset();
				return null;
			}
			short opCode = in.getShort();
			int sessionId = in.getInt();
			int serial = in.getInt();
			byte type = in.get();
			byte[] data = new byte[len - 11];
			in.get(data);
			ProxyPacket packet = new ProxyPacket(opCode, IoBuffer.wrap(data), sessionId, serial, type);
			return packet;
		}
		throw new IllegalArgumentException("ProxyPacket head error.");
	}

}
